package com.maserb.monitor.dataCenter.handler;

import com.maserb.monitor.common.AjaxResult;
import com.maserb.monitor.common.AjaxUtils;
import com.maserb.monitor.common.Func_T;
import com.maserb.monitor.dataCenter.model.EigenValueRequest;
import com.maserb.monitor.dataCenter.model.EigenValueRequestKey;
import com.maserb.monitor.dataCenter.model.EigenValueResponse;
import com.maserb.monitor.dataCenter.model.EigenValueResponseResult;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.*;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.CopyOnWriteArrayList;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

@Component
public class EigenValueRequestHandler {

    private Map<EigenValueRequestKey, List<EigenValueRequest>> eigenValueRequests = new ConcurrentHashMap<>();

    private ExecutorService fixedThreadPool = Executors.newFixedThreadPool(4);

    public void subscribe(EigenValueRequest request) {
        if (!eigenValueRequests.containsKey(request.getKey())) {
            eigenValueRequests.put(request.getKey(), new CopyOnWriteArrayList<>());
        }

        List<EigenValueRequest> requests = eigenValueRequests.get(request.getKey());
        requests.add(request);
    }

    public void publish(EigenValueResponse response) {
        fixedThreadPool.execute(() -> {
            if (eigenValueRequests.containsKey(response.getKey())) {
                for (EigenValueRequest request : eigenValueRequests.get(response.getKey())) {
                    if (request.getResponse() != null) {
                        AjaxResult<EigenValueResponseResult> result = AjaxUtils.process(new Func_T<EigenValueResponseResult>() {
                            @Override
                            public EigenValueResponseResult invoke() throws Exception {
                                return response.getResult();
                            }
                        });
                        request.getResponse().setResult(result);
                    }
                }

                eigenValueRequests.remove(response.getKey());
            }
        });
    }
}
